package day16.myreflect02;

import day16.myreflect01.Student;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * @author Xiao
 * @date 2021/8/10
 */
public class ConstructorDemo02 {
    /**
     * 利用Constructor创建对象
     * 	T newInstance(Object... initargs)：根据指定的构造方法创建对象
     * 	setAccessible(boolean flag)：设置为true,表示取消访问检查
     */
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        Class<?> clazz = Class.forName("day16.myreflect02.Student02");
        //公共的Constructor创建学生对象
        Constructor<?> con1 = clazz.getConstructor();
        Constructor<?> con2 = clazz.getConstructor(String.class, Integer.class);
        Student02 stu1 = (Student02) con1.newInstance();
        Student02 stu2 = (Student02) con2.newInstance("阿良", 24);
        System.out.println(stu1);
        System.out.println(stu2);
        //简写空参Constructor创建学生对象  →  已经过时
        Student02 stu3 = (Student02) clazz.newInstance();
        System.out.println(stu3);
        //私有Constructor创建学生对象 → IllegalAccessException
        Constructor<?> declCon = clazz.getDeclaredConstructor(String.class);
        //被private修饰的成员，需要临时取消访问检查
        declCon.setAccessible(true);
        Student02 stu4 = (Student02) declCon.newInstance("左右");
        System.out.println(stu4);

    }
}
